<template>
  <div class="register-page">
    <div class="form-container">
      <div class="title">注册</div>
      <form @submit.prevent="register">
        <input type="text" class="username" v-model="username" placeholder="请输入你的用户名">
        <div class="error">{{ errorMessage }}</div>
        <input type="password" class="password" v-model="password" placeholder="请输入你的密码">
        <div class="error">{{ errorMessage }}</div>
        <input type="password" class="pwdagain" v-model="pwdagain" placeholder="请再次输入你的密码">
        <div class="error">{{ errorMessage }}</div>
        <button type="submit" class="register-btn">注册</button>
        <div class="login">
          <RouterLink to="/login">返回登录</RouterLink>
        </div>
      </form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { useUserStore } from '../stores/userStore'; // 导入你的store

export default defineComponent({
  name: 'RegisterComponent',
  setup() {
    const userStore = useUserStore(); // 使用store
    const username = ref('');
    const password = ref('');
    const pwdagain = ref('');
    const errorMessage = ref('');

    const validUsername = computed(() => username.value.trim() !== '');
    const validPassword = computed(() => password.value.trim() !== '' && password.value === pwdagain.value);

    const register = () => {
      errorMessage.value = ''; // 重置错误信息
      if (!validUsername.value) {
        errorMessage.value = '用户名不能为空';
        return;
      } else if (!validPassword.value) {
        errorMessage.value = '密码不能为空或两次输入的密码不一致';
        return;
      }

      userStore.setUser(username.value, password.value); // 使用store的setUser方法
    };

    return {
      username,
      password,
      pwdagain,
      errorMessage,
      validUsername,
      validPassword,
      register
    };
  }
});
</script>

<style scoped>
.title {
  padding: 30px;
  font-size: 32px;
}

.register-page {
  text-align: center;
  position: absolute;
  top: 15%;
  left: 38%;
}

.form-container {

  height: 500px;
  width: 400px;
  padding: 20px;
  background-image: linear-gradient(to right, #f56ca5, #6ec4ec);
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
  /* 添加阴影以增强视觉效果 */
}

input[type="text"],
input[type="password"],
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 30px;
}

.register-btn {
  width: 100%;
  padding: 10px 20px;
  background-image: linear-gradient(to right, #6ec4ec, #f56ca5);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.login {

  font-size: 16px;
  text-align: center;
  cursor: pointer;
  margin-top: 30px;
  /* 返回登录与页面底部的间隔 */
}
</style>